package com.taylor.community.config;

import com.taylor.community.util.CommunityConstant;
import com.taylor.community.util.CommunityUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Security配置类
 * @author 26925
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {
    @Override
    public void configure(WebSecurity web) throws Exception {
        //忽略对静态资源的拦截
        web.ignoring().antMatchers("/resources/**");
    }
//    //没有写认证管理器 那程序会走我们自己写的login请求的逻辑
//    //其实Security内部认证完后会将认证信息存到UsernamePasswordAuthenticationToken
//    //而这个token会有一个filter获取到并存入SecurityContext里 后面进行授权时依据SecurityContext里的认证结果
//    //我们的解决方案是在LoginTicketInterceptor拦截器中手动获取认证结果并将认证结果装进SecurityContext
//    @Override
//    //认证管理器
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        super.configure(auth);
//    }

    /**
     * 进行授权处理
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //放行所有请求
        http.authorizeRequests()
                .anyRequest().permitAll();
        http.authorizeRequests()
                //需要进行过滤的请求路径
                .antMatchers(
                        "/user/setting",
                        "/user/upload",
                        "/discuss/add",
                        "/comment/add/**",
                        "/letter/**",
                        "/notice/**",
                        "/like",
                        "/follow",
                        "/unfollow"
                )
                //拥有的权限类型
                .hasAnyAuthority(
                        AUTHORITY_ADMIN,
                        AUTHORITY_USER,
                        AUTHORITY_MODERATOR
                )
                .antMatchers(
                        "/discuss/top",
                        "/discuss/wonderful"
                )
                .hasAnyAuthority(
                        AUTHORITY_MODERATOR
                )
                .antMatchers(
                        "/discuss/delete",
                        "/data/**",
                        "/actuator/**"
                )
                .hasAnyAuthority(
                        AUTHORITY_ADMIN
                )
                .anyRequest().permitAll()//除了上述的路径 其余路径的请求都可以通过filter
                .and().csrf().disable(); //关闭Security的防止csrf攻击的功能
        //权限不足时处理
        http.exceptionHandling()
                //第一种情况：没有登录
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                        String xRequestedWith = httpServletRequest.getHeader("x-requested-with");
                        //若为异步请求 返回JSON格式字符串
                        if("XMLHttpRequest".equals(xRequestedWith)){
                            httpServletResponse.setContentType("application/plain;charset=utf-8");
                            //字符流 用于向前台输出内容
                            PrintWriter writer = httpServletResponse.getWriter();
                            writer.write(CommunityUtil.getJSONString(403,"您还没有登录哦！"));
                        }
                        //若为普通请求 重定向到登录页面
                        else{
                            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login");
                        }

                    }
                })
                //第二种情况：已经登录，但权限不足
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
                        String xRequestedWith = httpServletRequest.getHeader("x-requested-with");
                        if("XMLHttpRequest".equals(xRequestedWith)){
                            httpServletResponse.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = httpServletResponse.getWriter();
                            writer.write(CommunityUtil.getJSONString(403,"您的权限不足哦！"));
                        }
                        else{
                            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/denied");
                        }
                    }
                });
        //Security底层默认拦截logout请求 Filter在Controller之前拦截该请求
        //那么当后续我们访问logout时 会被拦截 所以手动覆盖默认的逻辑就能执行我们自己的logout请求
        //让Security底层去拦截我们项目根本没有的请求路径
        http.logout().logoutUrl("/securityLogout");
    }


}
